<template>
  <div class="form-container">
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item v-if="isLogin">
        <el-alert
            :title="errorMessage"
            type="error" show-icon>
        </el-alert>
      </el-form-item>

      <el-form-item label="用户名">
        <el-input placeholder="用户名" v-model="userName"></el-input>
      </el-form-item>
      <el-form-item label='密码'>
        <el-input placeholder="密码" v-model="password" show-password></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type='primary' @click="login()">登录</el-button>
        <el-button type='primary'>注册</el-button>
        <el-button type='primary'>忘记密码</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      userName: '',
      password: '',
      isLogin: false,
      errorMessage: ''
    }
  },
  methods:
      {
        login() {
          if (!this.userName) {
            this.errorMessage = '用户名不能为空';
            this.isLogin = true;
            return;
          }
          if (!this.password) {
            this.errorMessage = '密码不能为空';
            this.isLogin = true;
            return;
          }
          this.$http.post('http://localhost:3000/users/login', {'userName': this.userName, 'password': this.password})
              .then(result => {
                if (result.status === 200 && result.data.status === 0) {
                  localStorage.setItem("token", result.data.data.token);
                  localStorage.setItem("_id", result.data.data.user[0]._id);
                  localStorage.setItem("userName", result.data.data.user[0].userName);
                  this.$router.go(-1);
                } else {
                  this.errorMessage = '用户名或密码错误, 请重新登录 + errorMessage' + result.data.message;
                  this.isLogin = true;
                }
              })
              .catch((error) => {
                this.errorMessage = '登录失败,请重新登录, 错误信息为: ' + error;
                this.isLogin = true;

              })
        }
      }
}

</script>


<style lang="css" scoped>
.form-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  /* 填充整个视口高度

   //position: absolute;
   //top: 50%;
   //left: 50%;
   //transform: translate(-50%, -50%);
   //width: 50%; /* 可以根据实际情况调整表单宽度 */
  //max-width: 600px; /* 最大宽度限制，可选 */
  //background-color: #fff; /* 添加背景色，防止透明时看到底层内容 */
  //padding: 20px; /* 可选，增加内边距 */
  //box-sizing: border-box; /* 必须，使得内边距包含在总宽度内 */
}
</style>/